package org.ezplatform.office.meeting.info.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.mobile.util.common.service.CommonService;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.info.dao.ApplyRecordDao;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.entity.MeetingScope;
import org.ezplatform.office.meeting.info.entity.SignedInfo;
import org.ezplatform.office.meeting.info.web.rest.ApplyRecordApiMobileController;
import org.ezplatform.office.meeting.memo.entity.MemoInfo;
import org.ezplatform.office.meeting.memo.service.MemoInfoService;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.setting.base.service.BaseSetService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.category.dao.BoardroomCategorySetDao;
import org.ezplatform.office.meeting.setting.category.entity.BoardroomCategorySet;
import org.ezplatform.office.meeting.setting.serve.service.ServeSetService;
import org.ezplatform.office.meeting.setting.type.service.MeetingTypeService;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;

@Service
@Transactional
public class ApplyRecordDingService extends BaseService<ApplyRecord, String>{
    
	private final static Logger LOGGER = LoggerFactory.getLogger(ApplyRecordDingService.class);
	
    private int currentPageNum = 0;
    private int pageSizeNum = 0;
    private int startLimitNum = 0;
    
    @Autowired
    private ApplyRecordDao dao;
    
    @Autowired
	private CommonService commonService;
    
    @Autowired
    private BoardroomSetService boardroomSetService;
    
    @Autowired
    private BaseSetService baseSetService;

    @Autowired
    private MeetingScopeService meetingScopeService;
    
    @Autowired
	private ServeSetService serveSetService;
    
    @Autowired
    private SignedInfoService signedInfoService;

    @Autowired
    private MemoInfoService memoInfoService;
    
    @Autowired
    private NoticeInfoService noticeInfoService;

    @Autowired
    private UserApiService userApiService;
    
    @Autowired
    private OrgApiService orgApiService;
    
    @Autowired
    private SignedAddressService signedAddressService;
    
    @Autowired
    private AttachmentUtilsService attachmentUtilsService;
    
    @Autowired
    private BoardroomCategorySetDao categoryDao;
    
    @Autowired
    private MeetingTypeService meetingTypeService;
    
    @Autowired
    private MeetingUtils meetingUtils;
    
    @Autowired
    private RestClient restClient;
    
    @Override
    protected JpaBaseDao<ApplyRecord, String> getEntityDao() {
        return dao;
    }

    /**
     * 查询会议list列表数据信息
     * @param currentPage
     * @param pageSize
     * @param userId
     * @param corpId
     * @param type 0:
     * @return
     */
    public List<Map> getApplyRecordList(String currentPage, String pageSize, String userId,
            String corpId, String type,String isCountType) {
        List<Map> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(currentPage)){
            this.currentPageNum = Integer.valueOf(currentPage);
        }
        
        if(StringUtils.isNotEmpty(pageSize)){
            this.pageSizeNum = Integer.valueOf(pageSize);
        }
       this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select omapr.id applyRecordid,omapr.createdBy,sysu.user_name userName,omapr.name applyRecordName,");
        sql.append("omapr.start_time startDateTime,omapr.end_time endDateTime,ombs.name boardroomName,omni.id noticeInfoId,");
        sql.append("omni.type type,omni.status as status from oa_meeting_notice_info omni ");
        sql.append("left join oa_meeting_apply_record omapr on omni.apply_record_id = omapr.id ");
        sql.append("left join sys_user sysu on sysu.id = omapr.createdBy ");
        sql.append("left join oa_meeting_boardroom_set ombs on omapr.boardroom_id =ombs.id ");
        sql.append("where omni.corp_id=:corpId and omapr.status in(0,1) and omni.notice_user_id in(:userId) and omni.status not in(1) and omni.is_delete='0' ");
        sql.append("order by omni.type asc,omni.createdDate desc ");
        paramMap.put("corpId", corpId);
        paramMap.put("userId", userId);

        if(isCountType.equals("0")){
			list = super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);
        }else{
			list = super.findByListNativeQuery(sql.toString(), "", paramMap);
		}
        return list;
    }

    /**
     * 查询会议content(移动端新建或重新发起)
     * @param request 
     * @param applyRecordId
     * @param userId 
     * @param content
     * @return
     */
    public Map<String, Object> getApplyRecordContent(String applyRecordId, String userId,String corpId,String token) {
    	Map<String,Object> map = new HashMap<String,Object>();
		List<Map> boardroomSetList = this.boardroomSetService.getBoardroomSetList(corpId);//查看会议室
		map.put("boardroomSetList", boardroomSetList);
		List<Map<String,String>> noticeTypeList = this.baseSetService.getBaseSetList(corpId);//会议提醒方式
	    map.put("noticeTypeList", noticeTypeList);
	    String noticeType = commonService.getSysParamValueByMark(corpId, token,"sysImType");
	    map.put("noticeType", noticeType);
        List<Map<String,String>> addressList = new ArrayList<>();//会议签到地址
        List<Map<String,String>> emceeUserList = new ArrayList<Map<String,String>>();//默认主持人
        ApplyRecord applyRecord = null;
        BoardroomSet boardroomSet = null;
        if(StringUtils.isNoneEmpty(applyRecordId)){
            applyRecord = this.findOne(applyRecordId);
            if(applyRecord != null){
            	String boardroomId = applyRecord.getBoardroomId();
            	List serveSetList = null;
            	if(StringUtils.isNotEmpty(boardroomId)) {
            		serveSetList = this.serveSetService.getBoardRoomServeTreeDataList(corpId,boardroomId);//会议服务
            		boardroomSet = this.boardroomSetService.findOne(boardroomId);
            	}
            	map.put("serveSetList", serveSetList);
               	if(applyRecord.getIsSigned() == 1){//会议启动签到
	                 String signedType = applyRecord.getSignedType();
	                 if(signedType!=null && ("1".equals(signedType) || "2".equals(signedType))){
	                	 addressList = this.signedAddressService.findByARecordId(applyRecordId);
	                 }
	           	}
            }
        }
        if(applyRecord == null){
			applyRecord = new ApplyRecord();
			//主持人
			Map<String,String> emceeDingMap = new HashMap<String,String>();
			Map<String,Object> uasMap = this.userApiService.getUser(userId, corpId, "", token);
			if(uasMap != null){
				emceeDingMap.put("scopeType", "user");
				emceeDingMap.put("scopeName", (String)uasMap.get("userName"));
				emceeDingMap.put("imageId", StringUtils.null2String(uasMap.get("outsideLink")));
				emceeDingMap.put("scopeValue",(String)uasMap.get("id"));
				emceeUserList.add(emceeDingMap);
			}
		}
        map.put("meetingTypes", meetingTypeService.getMeetingTypes(corpId));
        map.put("applyRecord", applyRecord);
        map.put("boardroomSet", boardroomSet);
        map.put("emceeUserList", emceeUserList);
        map.put("addressList", addressList);
        return map;
    }
    
    /**
     * 查询会议content(移动端我的会议详情)
     * @param request 
     * @param applyRecordId
     * @param userId 
     * @param content
     * @return
     */
    public Map<String, Object> getViewApplyRecordContent(HttpServletRequest request, String applyRecordId, String userId,String corpId,String token) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	List<Map<String,String>> addressList = new ArrayList<>();//会议签到地址
    	List<Map> serveSetCheckList = new ArrayList<Map>();//会议申请选中的会议服务
    	List<Map<String,String>> noticeTypeCheckList = new ArrayList<Map<String,String>>();//会议申请选中的会议提醒
    	String isCreateUser = "0";//是否是创建人 0：否  1：是
    	String isEmceeUser = "0";//是否是主持人 0：否  1：是
    	String isMemoUser = "0";//是否是纪要员 0：否  1：是
    	String isAttendUser = "0";//是否是参会人 0：否 1：是
    	String isAttendants = "0";//是否是会议列席人 0：否 1：是
    	SignedInfo signedInfo = null;
    	ApplyRecord applyRecord = this.findOne(applyRecordId);
    	BoardroomSet boardroomSet = null;
    	if(applyRecord != null){
//			String qrCodeAttachId = applyRecord.getQrcodeAttach();
//			if(StringUtils.isNotEmpty(qrCodeAttachId)){
//				List<Map<String, String>> images = this.attachmentUtilsService.getAttachmentByIds(qrCodeAttachId, corpId, token);
//				if(images!=null && images.size()>0){
//					Map<String, String> image = images.get(0);
//					String url = GlobalConstant.getFlexServerPath(request);
//					map.put("image", image.get("imageUrl"));
//				}
//			}
			
			String boardroomId = applyRecord.getBoardroomId();
			if(StringUtils.isNotEmpty(boardroomId)) {
				boardroomSet = this.boardroomSetService.findOne(boardroomId);
				List serveSetList = this.serveSetService.getBoardRoomServeTreeDataList(corpId,boardroomId);//会议服务
            	map.put("serveSetList", serveSetList);
			}
			
			serveSetCheckList = this.serveSetService.getServeSetCheckList(applyRecord.getMeetingServe());
			noticeTypeCheckList = this.baseSetService.getBaseSetCheckList(request, applyRecord.getNoticeType());
			//发起人
			String createdBy = applyRecord.getCreatedBy();
			Map<String, Object> userMap = this.userApiService.getUser(createdBy, corpId, "", token);
			map.put("createdName", "");
			if(userMap != null){
				map.put("createdName", userMap.get("userName"));
			}
			if(createdBy.equals(userId)){//是否是发起人
				isCreateUser = "1";
			}
			//主持人
			List<String> eScopeList = new ArrayList<>();
			eScopeList.add(applyRecord.getEmceeUser());
			
			List<MeetingScope> emceeUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
			if(emceeUserScopeList!=null && emceeUserScopeList.size()>0){
				for(MeetingScope m : emceeUserScopeList){
					String scopeValue = m.getScopevalue();
					if(scopeValue.equals(userId)){
						isEmceeUser = "1";
					}
				}
			}
			//纪要员
			List<String> mScopeList = new ArrayList<>();
			mScopeList.add(applyRecord.getMemoUser());
			List<MeetingScope> memoUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
			if(memoUserScopeList!=null && memoUserScopeList.size()>0){
				for(MeetingScope m : memoUserScopeList){
					String scopeValue = m.getScopevalue();
					if(scopeValue.equals(userId)){
						isMemoUser = "1";
					}
				}
			}
			List<String> unitorgList = this.orgApiService.getOrgIdsByUserIds(userId, corpId, "", "2", token);
			//参会人员
			List<String> aScopeList = new ArrayList<>();
			aScopeList.add(applyRecord.getAttendUser());
			List<MeetingScope> attendUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
			if(attendUserScopeList!=null && attendUserScopeList.size()>0){
				if(unitorgList==null){
					unitorgList = new ArrayList<>();
				}
				unitorgList.add(userId);
				for(MeetingScope m : attendUserScopeList){
					String scopeValue = m.getScopevalue();
					for(String uuoStr : unitorgList){
						if(uuoStr.equals(scopeValue)){
							isAttendUser = "1";
							break;
						}
					}
					if("1".equals(isAttendUser)){
						break;
					}
				}
			}
			
			//会议列席人
			List<String> maScopeList = new ArrayList<>();
			maScopeList.add(applyRecord.getMeetingAttendants());
			List<MeetingScope> attendantsScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "meeting_attendants", maScopeList,true);
			if(attendantsScopeList!=null && attendantsScopeList.size()>0){
				if(unitorgList==null){
					unitorgList = new ArrayList<>();
				}
				unitorgList.add(userId);
				for(MeetingScope m : attendantsScopeList){
					String scopeValue = m.getScopevalue();
					for(String uuoStr : unitorgList){
						if(uuoStr.equals(scopeValue)){
							isAttendants = "1";
							break;
						}
					}
					if("1".equals(isAttendants)){
						break;
					}
				}
			}
			
			//查询会议签到
			signedInfo = this.signedInfoService.getSignedInfo(userId,applyRecordId);
			if(signedInfo==null){
				signedInfo = new SignedInfo();
			}
			//会议纪要
			MemoInfo memoInfo = this.memoInfoService.getMemoInfoByApplyRecordId(applyRecordId);
			if(memoInfo == null){
				memoInfo = new MemoInfo();
			}
			map.put("memoInfo", memoInfo);
			String signedDateTime = "";
			if(applyRecord.getIsSigned()==1){//会议启动签到
				String startDateTime = applyRecord.getStartTime();
				String signedTime = applyRecord.getSignedTime();
				String signedTimeStr = this.getDateTimeStr(startDateTime.substring(11, 16), Integer.valueOf(signedTime), 1);
				signedDateTime = startDateTime.substring(0,10)+" "+signedTimeStr+":00";
				String signedType = applyRecord.getSignedType();
				if(signedType!=null && ("1".equals(signedType) || "2".equals(signedType))){
					addressList = this.signedAddressService.findByARecordId(applyRecordId);
				}
			}
			map.put("signedDateTime", signedDateTime);
		}
    	List<Map> boardroomSetList = this.boardroomSetService.getBoardroomSetList(corpId);//查看会议室
		map.put("boardroomSetList", boardroomSetList);
		List<Map<String,String>> noticeTypeList = this.baseSetService.getBaseSetList(corpId);//会议提醒方式
	    map.put("noticeTypeList", noticeTypeList);
    	map.put("meetingTypes", meetingTypeService.getMeetingTypes(corpId));
    	map.put("signedInfo", signedInfo);
    	map.put("applyRecord", applyRecord);
    	map.put("serveSetCheckList", serveSetCheckList);
    	map.put("boardroomSet", boardroomSet);
    	map.put("noticeTypeCheckList", noticeTypeCheckList);
    	map.put("isCreateUser", isCreateUser);
    	map.put("isMemoUser", isMemoUser);
    	map.put("isEmceeUser", isEmceeUser);
    	map.put("isAttendUser", isAttendUser);
    	map.put("addressList", addressList);
    	return map;
    }
    
    /**
     * 查询会议content(移动端通知)
     * @param request 
     * @param applyRecordId
     * @param userId 
     * @param content
     * @return
     */
    public Map<String, Object> getApproveApplyRecordContent(String applyRecordId, String corpId,String token) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	List<Map> serveSetCheckList = new ArrayList<Map>();//会议申请选中的会议服务
    	ApplyRecord applyRecord = this.findOne(applyRecordId);
    	BoardroomSet boardroomSet = null;
		if(applyRecord !=null ){
			String boardroomId = applyRecord.getBoardroomId();
			if(StringUtils.isNotEmpty(boardroomId)) {
				boardroomSet = this.boardroomSetService.findOne(boardroomId);
			}
			serveSetCheckList = this.serveSetService.getServeSetCheckList(applyRecord.getMeetingServe());
			//发起人
			String createdBy = applyRecord.getCreatedBy();
			Map<String, Object> userMap = this.userApiService.getUser(createdBy, corpId, "", token);
			map.put("createdName", "");
			if(userMap != null){
				map.put("createdName", userMap.get("userName"));
			}
		}
    	map.put("applyRecord", applyRecord);
    	map.put("serveSetCheckList", serveSetCheckList);
    	map.put("boardroomSet", boardroomSet);
    	return map;
    }
    
    /**
     * 查询会议content(移动端会议纪要)
     * @param request 
     * @param applyRecordId
     * @param userId 
     * @param content
     * @return
     */
    public Map<String, Object> getMemoApplyRecordContent(String applyRecordId, String corpId,String token) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	ApplyRecord applyRecord = this.findOne(applyRecordId);
    	if(applyRecord != null ){
			String boardroomId = applyRecord.getBoardroomId();
			BoardroomSet boardroomSet = null;
			if(StringUtils.isNotEmpty(boardroomId)) boardroomSet = this.boardroomSetService.findOne(boardroomId);
			//查询会议 参会人员  缺席人员
			List auList = new ArrayList();
			List noauList = new ArrayList();
			List<Map<String,String>> attendUserNameList = new ArrayList<Map<String,String>>();
			List<Map<String,String>> noAttendUserNameList = new ArrayList<Map<String,String>>();
			int isSigned = applyRecord.getIsSigned();
			if(isSigned==0){//会议签到：未开启
				//查询确认参会人员
				auList = this.noticeInfoService.getNoticeUserList(applyRecord.getId(),1);
				//查询未确认参会人员
				noauList = this.noticeInfoService.getNoticeUserList(applyRecord.getId(),0);
			}else{//会议签到：开启
				//查询签到参会人员
				auList = this.signedInfoService.getSignedUserList(applyRecord.getId(),1);
				//查询未签到参会人员
				noauList = this.signedInfoService.getSignedUserList(applyRecord.getId(),0);
			}
			if(auList!=null && auList.size()>0){
				for(int i=0;i<auList.size();i++){
					Map<String,String> auMap = new HashMap<String,String>();
					Object[] obj = (Object[])auList.get(i);
					String uId = StringUtils.null2String(obj[0]);
					if(StringUtils.isNotEmpty(uId)){
						auMap.put("scopeType", "user");
						auMap.put("scopeName", StringUtils.null2String(obj[1]));
						auMap.put("imageId", StringUtils.null2String(obj[2]));
						auMap.put("scopeValue",StringUtils.null2String(obj[3]));
						attendUserNameList.add(auMap);
					}
				}
			}
			if(noauList!=null && noauList.size()>0){
				for(int i=0;i<noauList.size();i++){
					Map<String,String> noauMap = new HashMap<String,String>();
					Object[] obj =  (Object[])noauList.get(i);
					String uId = StringUtils.null2String(obj[0]);
					if(StringUtils.isNotEmpty(uId)){
						noauMap.put("scopeType", "user");
						noauMap.put("scopeName", StringUtils.null2String(obj[1]));
						noauMap.put("imageId", StringUtils.null2String(obj[2]));
						noauMap.put("scopeValue",StringUtils.null2String(obj[3]));
						noAttendUserNameList.add(noauMap);
					}
				}
			}
			map.put("attendUserName", attendUserNameList);
			map.put("noAttendUserName", noAttendUserNameList);
			map.put("boardroomSet", boardroomSet);
    	}
    	map.put("applyRecord", applyRecord);
    	return map;
    }

    /**
     * 查询会议用户参会详细信息列表数据
     * @param request
     * @param currentPage
     * @param pageSize
     * @param id
     * @param type 0:未反馈； 1:确认参会； 2:已请假；
     * @param map
     * @return
     */
    public List<Map> getApplyRecordNoticeList(HttpServletRequest request, String currentPage,
            String pageSize, String id, String type, Map<String, Object> map) {
        List<Map> list = new ArrayList<>();

        Map<String, Object> params = new HashMap<>();
		params.put("applyRecordId", id);
        StringBuffer sql = new StringBuffer("");
        sql.append(" select omni.id,omni.notice_user_id userId,sysu.user_name userName from oa_meeting_notice_info omni ");
        sql.append(" left join sys_user sysu on omni.notice_user_id = sysu.id ");
        sql.append(" where omni.apply_record_id =:applyRecordId and omni.type=1 ");
        int status = 0;
        if("0".equals(type)){
            status = 0;
        }else if("1".equals(type)){
            status = 2;
        }else if("2".equals(type)){
            status = 3;
        }
        sql.append(" and omni.status =:status ");
		params.put("status", status);
        sql.append(" order by sysu.user_name ");

        //limit
        if(!"-2".equals(pageSize)){
        	if(StringUtils.isNotEmpty(currentPage)){
                this.currentPageNum = Integer.valueOf(currentPage);
            }
            if(StringUtils.isNotEmpty(pageSize)){
                this.pageSizeNum = Integer.valueOf(pageSize);
            }
           	this.startLimitNum = (this.currentPageNum-1) * this.pageSizeNum;
			list = super.findByListNativeQuery(sql.toString(), "", params, this.startLimitNum, this.pageSizeNum);
        }else{
			list = super.findByListNativeQuery(sql.toString(), "", params);
		}
       return list;
    }

    /**
     * 查询会议用户参会详细信息列表数据
     * @param request
     * @param currentPage
     * @param pageSize
     * @param id
     * @param type 3:未签到；4:已签到；
     * @param map
     * @return
     */
    public List<Map> getApplyRecordSigned(HttpServletRequest request, String currentPage,
            String pageSize, String id, String type, Map<String, Object> map) {
        List<Map> list = new ArrayList<>();

        Map<String, Object> params = new HashMap<>();
        params.put("applyRecordId", id);
        StringBuffer sql = new StringBuffer("");
        sql.append(" select omsi.id,omsi.signed_user_id signedUserId,sysu.user_name userName from oa_meeting_signed_info omsi");
        sql.append(" join sys_user sysu on omsi.signed_user_id = sysu.id");
        sql.append(" left join oa_meeting_apply_record omar on omsi.apply_record_id = omar.id");
        sql.append(" where omsi.apply_record_id =:applyRecordId ");
    	if("3".equals(type)){
    		sql.append(" and ((omar.signed_type='0' and omsi.is_signed!='s') ");
    		sql.append(" or (omar.signed_type='1' and omsi.is_signed!='d') ");
    		sql.append(" or (omar.signed_type='2' and omsi.is_signed!='sd') ");
    		sql.append("or (omar.signed_type!='0' and omar.signed_type!='1' and omar.signed_type!='2' and omar.signed_type is not null and omsi.is_signed!='xc') or omsi.is_signed ='0' or omsi.is_signed is null) ");
        }else if("4".equals(type)){
        	sql.append(" and ((omar.signed_type='0' and omsi.is_signed='s') ");
    		sql.append(" or (omar.signed_type='1' and omsi.is_signed='d') ");
    		sql.append(" or (omar.signed_type='2' and omsi.is_signed='sd') or (omar.signed_type!='0' and omar.signed_type!='1' and omar.signed_type!='2' and omar.signed_type is not null and omsi.is_signed='xc')  or omsi.is_signed ='0') ");
        }
        sql.append(" order by sysu.user_name");

        //limit
        if(!"-2".equals(pageSize)){
        	if(StringUtils.isNotEmpty(currentPage)){
                this.currentPageNum = Integer.valueOf(currentPage);
            }
            if(StringUtils.isNotEmpty(pageSize)){
                this.pageSizeNum = Integer.valueOf(pageSize);
            }
           this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
            list = super.findByListNativeQuery(sql.toString(), "", params, this.startLimitNum, this.pageSizeNum);
        }else{
			list = super.findByListNativeQuery(sql.toString(), "", params);
		}
       return list;
    }

    /**
     * 修改会议状态
     * @param id
     * @param status
     * @param noticeInfoId 
     * @param reason 
     */
    public void editApplyRecordInfo(String id, String status, String reason, String type, String token) {
        ApplyRecord applyRecord = new ApplyRecord();
        applyRecord = this.findOne(id);
        applyRecord.setReason(reason);
        applyRecord.setStatus(Integer.valueOf(status));
        if(StringUtils.isNotEmpty(type)){
			//保存会议
			applyRecord = this.save(applyRecord);
		}
        String applyRecordId = applyRecord.getId();
        if("0".equals(status)){//申请中
            
        }else if("1".equals(status)){//未召开
            /*List<String> noticeInfoList = new ArrayList<String>();
            noticeInfoList.add(noticeInfoId);*/
            //修改会议申请通知状态
            //this.noticeInfoService.deleteByListIds(noticeInfoList);
            this.noticeInfoService.deleteApproveNotice(applyRecordId);
            //发送会议审批通过通知
            //this.noticeInfoService.addNoticeInfoByApplyrecord(applyRecord,1,token);
            //新建会议签到数据
            if(applyRecord.getIsSigned()==1){
                this.signedInfoService.addSignedInfoByApplyrecord(applyRecord,token);
            }
        }else if("2".equals(status)){//已驳回
            /*List<String> noticeInfoList = new ArrayList<String>();
            noticeInfoList.add(noticeInfoId);*/
            //修改会议申请通知状态
            //this.noticeInfoService.deleteByListIds(noticeInfoList);
            this.noticeInfoService.deleteApproveNotice(applyRecordId);
        }else if("3".equals(status)){//已取消
            //删除会议申请通知、会议通知、会议签到
        	//删除相关签到信息
        	this.signedInfoService.deleteSignInfo(id);
        	//删除相关定位签到地址信息
        	this.signedAddressService.deleteSignAddress(id);
        	//删除相关通知
        	this.noticeInfoService.deleteByApplyrecord(id);
        }else if("4".equals(status)){//进行中
            
        }else if("5".equals(status)){//已结束
            
        }
    }

    /**
     * 删除会议通知
     * @param id
     */
    public void deleteApplyRecord(String id) {
        this.dao.deleteApplyRecord(id);
    }
    
    public String getApplyRecordByRoomId(String boardRoomId,String date,String corpId){
    	String result = "";
    	List<ApplyRecord> list = new ArrayList<ApplyRecord>();
    	String startTime = date + " 00:00:00";
    	String endTime = date + " 23:59:59";
    	list = this.dao.getApplyRecordList(boardRoomId, startTime, endTime);
    	WebUser user=WebUtils.getCurrentUser();
    	Map<String,String>textParams=new HashMap<>();
		textParams.put("code", "meeting:meeting:03");
		textParams.put("userId", user.getUserId());
		String jsonStr = this.restClient.get("/system/permission/hasPermission", user.getJwtToken(), textParams);
		Map<String, Object> permission = JsonUtils.readValue(jsonStr);
		boolean isView=false;
		if("1".equals(permission.get("data"))) {
			isView=true;
		}
    	if(!list.isEmpty()){
    		Date searchStart = DateUtils.parseTime(startTime);
    		Date searchEnd = DateUtils.parseTime(endTime);
    		Calendar calendar = Calendar.getInstance();
    		for(int i=0;i<list.size();i++) {
    			ApplyRecord record = list.get(i);
				Date start = DateUtils.parseTime(record.getStartTime()+":00");
				if(searchStart.getTime() > start.getTime()){
					start = searchStart;
				}
				Date end = DateUtils.parseTime(record.getEndTime()+":00");
				if(searchEnd.getTime() < end.getTime()){
					end = searchEnd;
				}
				calendar.setTime(start);
				int hours = calendar.get(Calendar.HOUR_OF_DAY);
				int minute  = calendar.get(Calendar.MINUTE);
				int num = hours*4 + (minute/15);
				while(start.getTime() < end.getTime()){
					num ++;
					//点击会议室时间调度查看会议通知详情和是否有查看详情的权限
					result += num+"."+record.getId()+"."+isView + ",";
					start = DateUtils.addMinutes(start, 15);
				}
			}
    	}
    	if(!"".equals(result)){
    		result = result.substring(0,result.length()-1);
    	}
    	return result;
    }

    /**
     * 查询会议室使用详细
     * @param bsList
     * @param dateStrList
     * @return
     */
    public List<Map<String,Object>> getApplyRecordInfo1(List<BoardroomSet> bsList,List<String> dateStrList) {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        if(bsList!=null && bsList.size()>0){
            for(BoardroomSet bs : bsList){
            	BoardroomCategorySet set = this.categoryDao.findById(bs.getCategoryId()).get();
            	if(set == null){
            		continue;
            	}
                Map<String,Object> boardroomMap = new HashMap<String,Object>(); 
                List<Map<String,String>> listMap = new ArrayList<Map<String,String>>();
                String boardroomSetId = bs.getId();
                String bsStartTime = bs.getStartTime()+":00";
                String bsEndTime = bs.getEndTime()+":59";
                for(String dateStr : dateStrList){
                    String startDateStr = dateStr + " 00:00:00";
                    String endDateStr = dateStr + " 23:59:59";
                    //会议室开启的开始时间
                    Date bsStartDateTime = DateUtils.parseTime(dateStr+" "+bsStartTime);
                    //会议室开启的结束时间
                    Date bsEndDateTime = DateUtils.parseTime(dateStr+" "+bsEndTime);
                    
                    List<ApplyRecord> arList = this.dao.getApplyRecordList(boardroomSetId,startDateStr,endDateStr);
                    String backEndTime = dateStr+" 00:00:00";
                    if(arList!=null && arList.size()>0){
                        int len = arList.size();
                        for(int i=0;i<len;i++){
                        	Date backEndTimeDate = DateUtils.parseTime(backEndTime);
                            ApplyRecord applyRecord = arList.get(i);
                            String startTime = applyRecord.getStartTime()+":00";
                            String endTime = applyRecord.getEndTime()+":59";
                            Date startDateTime = DateUtils.parseTime(startTime);
                            
                            if(backEndTimeDate.getTime()<bsStartDateTime.getTime()){
                            	if(bsStartDateTime.getTime()>startDateTime.getTime()){//会议室开放时间>会议开始时间
                                	//会议室开始时间之前的记录
                                    Map<String,String> startMap = new HashMap<String,String>();
                                    startMap.put("boardroomId", boardroomSetId);
                                    startMap.put("type", "0");
                                    startMap.put("style",getStyleStr(backEndTime+" 00:00:00",startTime));
                                    backEndTime = startTime;
                                    listMap.add(startMap);
                            	}else{
                            		if(bsEndDateTime.getTime()<startDateTime.getTime()){
                            			
                                		
                                		
                            		}else{
                            			Map<String,String> startMap = new HashMap<String,String>();
                                        startMap.put("boardroomId", boardroomSetId);
                                        startMap.put("type", "0");
                                        startMap.put("style",getStyleStr(backEndTime,dateStr+" "+bsStartTime));
                                        backEndTime = dateStr+" "+bsStartTime;
                                        listMap.add(startMap);
                                        
                            		}
                            		Map<String,String> backStartMap = new HashMap<String,String>();
                                    backStartMap.put("boardroomId", boardroomSetId);
                                    backStartMap.put("type", "1");
                                    backStartMap.put("style",getStyleStr(backEndTime,startTime));
                                    backEndTime = startTime;
                                    listMap.add(backStartMap);
                            	}
                    		}else{
                    			Map<String,String> backStartMap = new HashMap<String,String>();
                                backStartMap.put("boardroomId", boardroomSetId);
                                backStartMap.put("type", "1");
                                backStartMap.put("style",getStyleStr(backEndTime,startTime));
                                backEndTime = startTime;
                                listMap.add(backStartMap);
                    		}
                            
                            Map<String,String> map = new HashMap<String,String>();
                            map.put("boardroomId", boardroomSetId);
                            map.put("type", "2");
                            map.put("style",getStyleStr(startTime,endTime));
                            backEndTime = endTime;
                            listMap.add(map);
                            
                            if(i == len-1){
                            	if(backEndTimeDate.getTime()<bsStartDateTime.getTime()){
                            		//会议室开始时间之前的记录
                                    Map<String,String> startMap = new HashMap<String,String>();
                                    startMap.put("boardroomId", boardroomSetId);
                                    startMap.put("type", "0");
                                    startMap.put("style",getStyleStr(backEndTime,dateStr+" "+bsStartTime));
                                    backEndTime = dateStr+" "+bsStartTime;
                                    listMap.add(startMap);
                            	}
                            }
                            
                        }
                    }
                    Date backEndDateTime = DateUtils.parseTime(backEndTime);
                    if(backEndDateTime.getTime()<bsEndDateTime.getTime()){
                        Map<String,String> backEndMap = new HashMap<String,String>();
                        backEndMap.put("boardroomId", boardroomSetId);
                        backEndMap.put("type", "1");
                        backEndMap.put("style",getStyleStr(backEndTime,dateStr+" "+bsEndTime));
                        listMap.add(backEndMap);
                        backEndTime = dateStr+" "+bsEndTime;
                    }
                    Map<String,String> endMap = new HashMap<String,String>();
                    endMap.put("boardroomId", boardroomSetId);
                    endMap.put("type", "0");
                    endMap.put("style",getStyleStr(backEndTime,dateStr+" 23:59:59"));
                    listMap.add(endMap);
                    boardroomMap.put("boardroomSet", bs);
                    boardroomMap.put("applyRecordListMap", listMap);
                    list.add(boardroomMap);
                }    
            }
        }
        
        return list;
    }
    
    public List<Map<String,Object>> getApplyRecordInfo(List<BoardroomSet> bsList,List<String> dateStrList) {
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        if(bsList!=null && bsList.size()>0){
            for(BoardroomSet bs : bsList){
            	BoardroomCategorySet set = this.categoryDao.findById(bs.getCategoryId()).get();
            	if(set == null){
            		continue;
            	}
                Map<String,Object> boardroomMap = new HashMap<String,Object>(); 
                List<Map<String,String>> listMap = new ArrayList<Map<String,String>>();
                String boardroomSetId = bs.getId();
                String bsStartTime = bs.getStartTime()+":00";
                String bsEndTime = bs.getEndTime()+":59";
                for(String dateStr : dateStrList){
                    String startDateStr = dateStr + " 00:00:00";
                    String endDateStr = dateStr + " 23:59:59";
                    Date currentEnd = DateUtils.parseTime(endDateStr);
                    //会议室开始时间之前的记录
                    Map<String,String> startMap = new HashMap<String,String>();
                    //startMap.put("time", "00:00-"+bsStartTime);
                    startMap.put("boardroomId", boardroomSetId);
                    startMap.put("type", "0");
                    startMap.put("width",getStyleStr(dateStr+" 00:00:00",dateStr+" "+bsStartTime));
                    startMap.put("left","0");
                    listMap.add(startMap);
                    List<ApplyRecord> arList = this.dao.getApplyRecordList(boardroomSetId,startDateStr,endDateStr);
                    if(arList!=null && arList.size()>0){
                        int len = arList.size();
                        for(int i=0;i<len;i++){
                            ApplyRecord applyRecord = arList.get(i);
                            String startTime = applyRecord.getStartTime()+":00";
                            String endTime = applyRecord.getEndTime()+":59";
                            Date endDate = DateUtils.parseTime(endTime);
                            
                            Map<String,String> map = new HashMap<String,String>();
                            map.put("boardroomId", boardroomSetId);
                            map.put("type", "2");
                            if(currentEnd.getTime()>endDate.getTime()){
                            	map.put("width",getStyleStr(startTime,endTime));
                            }else{
                            	map.put("width",getStyleStr(startTime,endDateStr));
                            }
                            map.put("left",getStyleStr(startDateStr,startTime));
                            listMap.add(map);
                        }
                    }
                    Map<String,String> endMap = new HashMap<String,String>();
                    endMap.put("boardroomId", boardroomSetId);
                    endMap.put("type", "0");
                    endMap.put("width",getStyleStr(dateStr+" "+bsEndTime,dateStr+" 24:00"));
                    endMap.put("left",getStyleStr(startDateStr,dateStr+" "+bsEndTime));
                    listMap.add(endMap);
                    boardroomMap.put("boardroomSet", bs);
                    boardroomMap.put("applyRecordListMap", listMap);
                    list.add(boardroomMap);
                }    
            }
        }
        
        return list;
    }
    
    private String getStyleStr(String startdDateTime,String endDateTime){
        double min = (DateUtils.parseTime(endDateTime, "yyyy-MM-dd HH:mm").getTime() - DateUtils.parseTime(startdDateTime, "yyyy-MM-dd HH:mm").getTime())/60000;
        double m = min*100/(360*4);
        //m = Math.ceil(m);
        return String.valueOf(m);
    }
    
    
    /**
     * 保存验证
     * @param id
     * @param checkdata
     * @param type
     * @param corpId
     * @return
     */
    public String checkApplyRecordInfo(String id, String checkdata, int type, String corpId) {
        String msg = "";
        List<ApplyRecord> list = new ArrayList<ApplyRecord>();
        if (type == 1) {// 验证名称
            if (StringUtils.isNotEmpty(id)) {// 编辑
                list = this.dao.getApplyRecordByName(id, checkdata, corpId);
            } else {// 新建
                list = this.dao.getApplyRecordByName(checkdata, corpId);
            }
        }
        if (list != null && list.size() > 0) {
            msg = this.getCheckMsgStr(type);
        }
        return msg;
    }
    
    
    /**
     * 验证报错返回msg信息
     * 
     * @param type
     * @return
     */
    private String getCheckMsgStr(int type) {
        String msg = "";
        switch (type) {
        case 1:
            msg = "您输入的会议名称已存在";
            break;
        default:
            msg = "会议时间段内已有其他会议";
            break;
        }
        return msg;
    }

    /**
     * 验证会议时间段
     * @param id
     * @param startTime
     * @param endTime
     * @param boardroomId
     * @param corpId
     * @return
     */
    public String checkApplyRecordDate(String id, String startTime, String endTime, String boardroomId, String corpId) {
        String msg = "";
        List<ApplyRecord> list = new ArrayList<ApplyRecord>();
        if (StringUtils.isNotEmpty(id)) {// 编辑
            list = this.dao.getApplyRecordSeDate(id, startTime,endTime,corpId,boardroomId);
        } else {// 新建
            list = this.dao.getApplyRecordSeDate(startTime,endTime,corpId,boardroomId);
        }
        if (list != null && list.size() > 0) {
            msg = this.getCheckMsgStr(2);
        }
        return msg;
    }

	/**
	 * 根据会议id改变会议状态
	 * @param status
	 * @param ids
	 * @return
	 */
    public int changeStatusById(int status, List<String> ids){
    	return this.dao.updApplyRecord(status, ids);
	}
    
    /**
     * 计算有效时间
     * @param subRecordDate
     * @param onWorkTime
     * @param onWorkBefore
     * @param type 0:相加 1:相减
     * @return
     */
    public String getDateTimeStr(String dateTime, int data,int type) {
        String hourStr = "";
        String minStr = "";
        String[] arr = dateTime.split(":");
        int hour =Integer.valueOf(arr[0]);
        int min = Integer.valueOf(arr[1]);
        if(type==0){//相加计算
            hour = hour + (data+min)/60;
            min =(data+min)-(data+min)/60*60;
        }else if(type==1){//相减计算
            for(int i=0;i<hour;i++){
                if(((i*60+min)-data)>=0){
                    hour = (hour-i);
                    min = (i*60+min)-data;
                    break;
                }
            }
        }
        if(hour<10){
            hourStr = "0" + hour;
        }else{
            hourStr = "" + hour;
        }
        if(min<10){
            minStr = "0" + min;
        }else{
            minStr = "" + min;
        }
        return hourStr + ":"+ minStr;
    }
    
    /**
     * 获取会议所有参与人信息
     * @param emceeUser
     * @param memoUser
     * @param attendUser
     * @return
     */
    public List<Map> getAllMeetingUsers(String emceeUser, String memoUser, String attendUser){
    	
    	LOGGER.debug("-----getAllMeetingUsers----");
    	List<String> userIds = new ArrayList<>();
		//主持人
        List<String> eScopeList = new ArrayList<>();
        eScopeList.add(emceeUser);
        List<MeetingScope> emceeUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
        if(emceeUserList != null && emceeUserList.size()>0){
        	userIds.add(emceeUserList.get(0).getScopevalue());
        }
        //纪要员
        List<String> mScopeList = new ArrayList<>();
        mScopeList.add(memoUser);
        List<MeetingScope> memoUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
        if(memoUserList!=null && memoUserList.size()>0){
        	userIds.add(memoUserList.get(0).getScopevalue());
        }
        //参会员
        List<String> aScopeList = new ArrayList<>();
        aScopeList.add(attendUser);
        List<MeetingScope> attendUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "attend_user", aScopeList,true);
        List<String> orgIds = new ArrayList<>();
        String type = "", value = "";
        if(attendUserList != null && attendUserList.size()>0){
        	for (MeetingScope scope : attendUserList) {
        		type = scope.getScopetype();
        		value = scope.getScopevalue();
        		if("user".equals(type)){
        			userIds.add(value);
        		}else if("org".equals(type)){
        			orgIds.add(value);
        		}
			}
        }
        Map<String, Object> paramsMap = new HashMap<>();
        
        List<String> orgAll = getChildrenOrParentIds(orgIds, "sys_org", "parent_id", "children", "is_delete=0", true);
        StringBuffer sql = new StringBuffer();
        sql.append("select id as value,user_name as text from sys_user where is_delete = 0");
        if(userIds!=null && userIds.size()>0) {
        	if(orgAll!=null && orgAll.size()>0){
            	sql.append(" and (id in (:userIds) or id in (select user_id from sys_org_user where org_id in (:orgAll)))");
            	paramsMap.put("userIds", userIds);
            	paramsMap.put("orgAll", orgAll);
            }else {
            	sql.append(" and id in (:userIds) ");
            	paramsMap.put("userIds", userIds);
            }
        }else if(orgAll!=null && orgAll.size()>0){
        	sql.append(" and id in (select user_id from sys_org_user where org_id in (:orgAll)) ");
        	paramsMap.put("orgAll", orgAll);
        }
        List<Map> list = super.findByListNativeQuery(sql.toString(), "", paramsMap);
		return list;
    }
    
    /**
	 * 根据附件id获取到附件的具体信息,并封装成钉钉app适应的格式
	 * @param attid 附件id用|分割
	 * @return
	 */
	public Object transformAttachmentPlanform2Dd(String attid, String token) {
		Object data = new JSONArray();
		if (StringUtils.isNotEmpty(attid)) {
			Map param2 = new HashMap();
			param2.put("fids", attid);
			try {
				String scopeMap1 = restClient.get("/cmp/attachment/getAttachmentInfos", token, param2);
				Map<String, Object> map1 = JsonUtils.readValue(scopeMap1);
				if (StringUtils.equals("success", StringUtils.null2String(map1.get("type")))) {
					data = map1.get("data");
				}
			} catch (Exception e) {
				e.printStackTrace();
//				System.out.println("钉钉APP获取附件获取失败");
//				System.out.println(e.getMessage());
			}
		}
		return data;
	}
	
	/**
	 * 查询已申请会议室列表数据
	 * @param request
	 * @return
	 */
    public List<Map> findApplyBoardroomListByPage(String currentPage, String pageSize, String userId,
            String corpId, String condition) {
        if(StringUtils.isNotEmpty(currentPage)){
            this.currentPageNum = Integer.valueOf(currentPage);
        }
        if(StringUtils.isNotEmpty(pageSize)){
            this.pageSizeNum = Integer.valueOf(pageSize);
        }
        this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
		sql.append("select omar.id, ombs.id boardroomId, ombs.name boardRoomName, ombc.name boardroomCateName, omar.start_time, omar.end_time,");
		sql.append(" ombs.address, omar.is_sync boardroomStatus, ombc.id cateId");
		sql.append(" from oa_meeting_apply_record omar,oa_meeting_boardroom_set ombs,oa_meeting_boardroom_cate ombc");
		sql.append(" where omar.boardroom_id=ombs.id and ombs.category_id=ombc.id and omar.corp_id=:corpId and omar.createdBy=:userId");
		sql.append(" and omar.status in (1,3,4,5)");
		if(StringUtils.isNotBlank(condition)) {
			sql.append(" and ombs.name like :boardroomName");
			paramMap.put("boardroomName", "%"+ condition +"%");
		}
		sql.append(" order by omar.createdDate desc");
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
        return super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);
    }
    
    /**
	 * 查询可以使用的会议室列表数据
	 * @param request
	 * @return
	 */
	public List<Map> findCanUseBoardroomListByPage(String currentPage, String pageSize, String userId,
            String isCycle,String corpId, String condition) {
		if(StringUtils.isNotEmpty(currentPage)){
            this.currentPageNum = Integer.valueOf(currentPage);
        }
        if(StringUtils.isNotEmpty(pageSize)){
            this.pageSizeNum = Integer.valueOf(pageSize);
        }
        this.startLimitNum= (this.currentPageNum-1) * this.pageSizeNum;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select omar.id, ombs.id boardroomId, ombs.name boardroomName, ombc.name boardroomCateName, omar.start_time, omar.end_time,");
		sql.append(" ombs.address, omar.is_sync boardroomStatus, ombc.id cateId, omar.cycle_id cycleId");
		sql.append(" from oa_meeting_apply_record omar");
//		if(StringUtils.isNotBlank(isCycle)) {
//			sql.append(" join (select min( start_time ) start_time, cycle_id FROM oa_meeting_apply_record ");
//			sql.append(" where is_cycle = 1 and cycle_id is not null group by cycle_id) t on omar.cycle_id=t.cycle_id and omar.start_time=t.start_time");
//		}
		sql.append(" left join oa_meeting_boardroom_set ombs on omar.boardroom_id=ombs.id");
		sql.append(" left join oa_meeting_boardroom_cate ombc on ombs.category_id=ombc.id");
		sql.append(" where omar.corp_id=:corpId and omar.createdBy=:userId and omar.is_sync=0 and omar.status=1");
		sql.append(" and omar.start_time > :now");
		paramMap.put("now", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm"));
		if(StringUtils.isNotBlank(isCycle)) {
			sql.append(" and omar.is_cycle = 1 and omar.cycle_id is not null");
		}
		if(StringUtils.isNotBlank(condition)) {
			sql.append(" and ombs.name like :boardroomName");
			paramMap.put("boardroomName", "%"+ condition +"%");
		}
		sql.append(" order by omar.createdDate desc");
		paramMap.put("corpId", corpId);
		paramMap.put("userId", userId);
		return super.findByListNativeQuery(sql.toString(), "", paramMap, this.startLimitNum, this.pageSizeNum);
	}
}